package com.miniapp.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.miniapp.entity.R;
import com.miniapp.entity.User;
import com.miniapp.service.UserService;
import com.miniapp.util.MiniAppUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author author
 * @date 2025-09-01 10:59
 */
@RestController
@RequestMapping("/api/auth/wechat")
@Api(tags = "微信授权接口")
public class WechatAuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private MiniAppUtil wechatUtil;

    /**
     * 微信小程序登录
     * @param param 包含code、encryptedData、iv等参数
     */
    @PostMapping("/login")
    @ApiOperation(value = "授权登录", notes = "授权登录")
    public R<Map<String, Object>> wechatLogin(@RequestBody Map<String, String> param) {
        String code = param.get("code");
        String encryptedData = param.get("encryptedData");
        String iv = param.get("iv");

        // 1. 调用微信接口获取session_key和openid
        Map<String, String> sessionInfo = wechatUtil.getSessionInfo(code);
        String openId = sessionInfo.get("openid");
        String sessionKey = sessionInfo.get("session_key");

        // 2. 查询用户是否已存在
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getOpenId, openId));

        // 3. 解密手机号(如果有)
        String phone = null;
        if (encryptedData != null && iv != null) {
            phone = wechatUtil.decryptPhone(encryptedData, sessionKey, iv);
        }

        // 4. 新用户创建账号
        if (user == null) {
            user = new User();
            user.setOpenId(openId);
            // 默认普通用户角色
            user.setRole("USER");
            // 生成默认用户名
            user.setUsername("wx_" + openId.substring(0, 8));
            // 默认密码加密存储
            user.setPassword(SecureUtil.md5("default_password"));
            // 设置创建时间
            user.setCreateTime(LocalDateTime.now());
        }

        // 5. 更新用户信息
        user.setSessionKey(sessionKey);
        user.setLastLoginTime(LocalDateTime.now());
        if (phone != null) {
            // 自动处理加密和脱敏
            user.setPhone(phone);
        }
        // 如果有头像信息则更新
        if (param.containsKey("avatarUrl")) {
            user.setAvatarUrl(param.get("avatarUrl"));
        }
        user.setUpdateTime(LocalDateTime.now());

        userService.saveOrUpdate(user);

        // 6. 生成JWT令牌返回(不包含敏感信息)
        String token = wechatUtil.generateToken(user);
        // 清除敏感信息
        user.setSessionKey(null);

        // 使用HashMap替代Map.of，兼容Java 8及以下版本
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("user", user);
        resultMap.put("token", token);
        return R.success(resultMap);
    }

    @GetMapping("/testLogin")
    @ApiOperation(value = "测试授权登录", notes = "测试授权登录")
    public R<Map<String, Object>> testLogin() {
        Map<String, Object> resultMap = new HashMap<>();
        User user = new User();
        user.setUsername("zhangsan");
        user.setId(100L);
        user.setRole("admin");
        user.setOpenId("xx1234");
        String token = wechatUtil.generateToken(user);
        resultMap.put("user", user);
        resultMap.put("token", token);
        return R.success(resultMap);
    }

}
